package org.small.shop.phone.api.process.users.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.small.shop.phone.api.process.users.pojo.HomeUsersVo;
import org.small.shop.phone.api.process.users.pojo.TblWxUsers;
import org.small.shop.phone.api.process.users.service.TblWxUsersService;
import org.small.shop.phone.api.utils.AppConstantUtils;
import org.small.shop.phone.api.utils.ReadProperties;
import org.small.shop.phone.api.utils.RedisOperator;
import org.small.shop.phone.api.utils.ShopJSONResult;
import org.small.shop.phone.api.utils.ftp.UploadUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class TblWxUsersController {

	private static Logger logger = LoggerFactory.getLogger(TblWxUsersController.class);

	@Resource
	private TblWxUsersService tblWxUsersService;

	@Resource
	private RedisOperator redisOperators;

	@PostMapping("/login/updateUserInfo")
	public ShopJSONResult updateUserInfo(TblWxUsers users, HttpServletRequest request) throws Exception {

		String openid = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(openid)) {
			try {
				tblWxUsersService.updateUsers(openid, users);
				return ShopJSONResult.ok();
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("修改用户信息失败!");
	}

	@PostMapping("/login/getHomeUser")
	public ShopJSONResult getHomeUser(HttpServletRequest request) throws Exception {

		String openid = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(openid)) {
			try {
				HomeUsersVo homeUsersVo = tblWxUsersService.getHomeUser(openid);
				return ShopJSONResult.ok(homeUsersVo);
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("获取会员信息失败!");
	}

	@PostMapping("/login/getUserInfo")
	public ShopJSONResult getUserInfo(HttpServletRequest request) throws Exception {

		String openid = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(openid)) {
			try {
				HomeUsersVo homeUsersVo = tblWxUsersService.getUserInfo(openid);
				return ShopJSONResult.ok(homeUsersVo);
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("获取会员信息失败!");
	}

	@PostMapping("/login/updataUserNickname")
	public ShopJSONResult updataUserNickname(HttpServletRequest request, String userNickname) throws Exception {

		String openid = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(openid) && !StringUtils.isEmpty(userNickname) && userNickname.length() <= 10) {
			try {
				tblWxUsersService.updataUserNickname(openid, userNickname);
				return ShopJSONResult.ok();
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("修改会员昵称失败!");
	}

	@PostMapping(value = "/login/uploadUserHeadImg")
	public ShopJSONResult uploadEmpHeadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		String openid = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(openid)) {

			String agreeCount = redisOperators.get(openid + AppConstantUtils.AGREE_COUNT_FLAG);
			if (!StringUtils.isEmpty(agreeCount) && Integer.parseInt(agreeCount) > AppConstantUtils.AGREE_COUNT) {
				return ShopJSONResult.errorMsg("更改头像过于频繁，请稍后再试！");
			}else if(StringUtils.isEmpty(agreeCount)) {
				agreeCount="0";
			}

			response.setHeader("Access-Control-Allow-Origin", "*");
			String maxHeadImgSize = ReadProperties.getInstance().getApplicationProperties()
					.getProperty("MAX_HEADIMAGE_SIZE");

			if (file == null || file.getSize() == 0L || StringUtils.isEmpty(file.getOriginalFilename()))
				return ShopJSONResult.errorMsg("上传头像不能为空!");

			if (!checkFileSize(file.getSize(), Integer.parseInt(maxHeadImgSize), "k")) {
				return ShopJSONResult.errorMsg("用户上传头像不能大于1M!");
			}

			// 头像图片允许上传的类型
			String picType = ReadProperties.getInstance().getApplicationProperties().getProperty("Agree_imageType");
			String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			if (picType != null && fileType != null && !picType.trim().contains(fileType.trim().toUpperCase())) {
				return ShopJSONResult.errorMsg("请上传有效格式的图片作为头像!");
			}

			InputStream inputStream = null;
			FileOutputStream fileOutputStream = null;
			try {

				String uploadPathDB = "/user/face/" + UploadUtils.generateRandonFileName(file.getOriginalFilename());
				String finalFacePath = "G:/shop" + uploadPathDB;
				File outFile = new File(finalFacePath);
				if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
					outFile.getParentFile().mkdirs();
				}

				fileOutputStream = new FileOutputStream(outFile);
				inputStream = file.getInputStream();
				IOUtils.copy(inputStream, fileOutputStream);

				// 保存用户的头像信息
				tblWxUsersService.uploadUserHeadImg(openid, uploadPathDB);

				// 保存一天内用户上传头像的次数
				redisOperators.set(openid + AppConstantUtils.AGREE_COUNT_FLAG, (Integer.parseInt(agreeCount) + 1) + "",
						24 * 60 * 60);

				return ShopJSONResult.ok("");

			} catch (Exception e) {
				e.printStackTrace();
				logger.info(e.getMessage());
				return ShopJSONResult.errorMsg("更改头像失败！");
			} finally {
				if (fileOutputStream != null) {
					fileOutputStream.flush();
					fileOutputStream.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			}

		}
		return ShopJSONResult.errorMsg("更改头像失败！");
		/*
		 * InputStream is = null; try {
		 * 
		 * is = file.getInputStream(); FtpConfig ftpConfig = FtpConfig.getInstance();
		 * String picNewName = UploadUtils.generateRandonFileName(originalFilename);
		 * 
		 * StringBuilder picSavePath = new StringBuilder();
		 * picSavePath.append("/").append("UserHeadImg").append("/");
		 * picSavePath.append(FormatUtils.getFormatDate(System.currentTimeMillis()));
		 * picSavePath.append("/").append(picNewName);
		 * 
		 * String realNetworkPath = FtpUtil.pictureFtpUpload(ftpConfig, picNewName,
		 * picSavePath.toString(), is); if (realNetworkPath != null) {
		 * 
		 * Map<String, String> map = new HashMap<String, String>();
		 * map.put("picSavePath", picSavePath.toString()); map.put("realNetworkPath",
		 * realNetworkPath); return ShopJSONResult.ok(map); } return
		 * ShopJSONResult.errorMsg("更改头像失败！"); } catch (IOException e) {
		 * logger.error(e.getMessage()); return ShopJSONResult.errorMsg("更改头像失败！"); }
		 */
	}

	/**
	 * 判断文件大小
	 *
	 * @param len  文件长度
	 * @param size 限制大小
	 * @param unit 限制单位（B,K,M,G）
	 * @return
	 */
	public static boolean checkFileSize(Long len, int size, String unit) {
		double fileSize = 0;
		if ("B".equals(unit.toUpperCase())) {
			fileSize = (double) len;
		} else if ("K".equals(unit.toUpperCase())) {
			fileSize = (double) len / 1024;
		} else if ("M".equals(unit.toUpperCase())) {
			fileSize = (double) len / 1048576;
		} else if ("G".equals(unit.toUpperCase())) {
			fileSize = (double) len / 1073741824;
		}
		if (fileSize > size) {
			return false;
		}
		return true;
	}

}
